package com.jeesuite.bestpl.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.jeesuite.bestpl.dto.User;
import com.jeesuite.bestpl.dto.WrapperResponseEntity;
import com.jeesuite.bestpl.dto.request.RegisterRequest;
import com.jeesuite.bestpl.security.LoginUserInfo;
import com.jeesuite.bestpl.security.SecurityUtil;
import com.jeesuite.bestpl.service.UserService;

@RestController
@RequestMapping("/api/user")
public class UserController {
	
	
	@Autowired
	private UserService userService;
    
	
	@RequestMapping(value = "regsiter", method = RequestMethod.POST)
	public ResponseEntity<WrapperResponseEntity<Object>> addUser(@RequestBody RegisterRequest request){
		userService.register(request);
		return new ResponseEntity<WrapperResponseEntity<Object>>(new WrapperResponseEntity<Object>(true),HttpStatus.OK);
	}
	
	@RequestMapping(value = "login", method = RequestMethod.POST)
	public ResponseEntity<WrapperResponseEntity<Object>> login(HttpServletRequest request,@RequestBody Map<String, String> params){
		String loginName = StringUtils.trimToEmpty(params.get("loginName"));
		String password = StringUtils.trimToEmpty(params.get("password"));
		
		User loginUser = userService.login(loginName, password);
	
		LoginUserInfo loginUserInfo = new LoginUserInfo(loginUser.getName());
		loginUserInfo.setId(loginUser.getId());
		request.getSession().setAttribute(SecurityUtil.LOGIN_SESSION_KEY, loginUserInfo);
		return new ResponseEntity<WrapperResponseEntity<Object>>(new WrapperResponseEntity<Object>(loginUserInfo),HttpStatus.OK);
	}

}
